import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/Layout'
import store from '@/store'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login')
    },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/Layout/components/home'),
          // 路由元信息
          meta: { isKeepAlive: true }
        },
        {
          path: '/question',
          component: () => import('@/views/Layout/components/question')
        },
        {
          path: '/user',
          component: () => import('@/views/Layout/components/user')
        },
        {
          path: '/video',
          component: () => import('@/views/Layout/components/video')
        }
      ]
    },
    {
      path: '/search',
      component: () => import('@/views/search')
    },
    {
      path: '/searchResult',
      component: () => import('@/views/searchResult')
    },
    {
      path: '/article/:id',
      component: () => import('@/views/article')
    },
    {
      path: '/userProfile',
      component: () => import('@/views/userProfile')
    },
    {
      path: '/userChat',
      component: () => import('@/views/userChat')
    }
  ]
})
// router.beforeEach((to, from, next) => {
//   if (to.path === '/user') {
//     // const token = store.state.user.token
//     if (localStorage.getItem('token')) {
//       // if (token) {
//       next()
//     } else {
//       next('/login')
//     }
//   } else {
//     next()
//   }
// })
// 需要认证的页面
const AuthUrls = ['/User', '/user', '/search']
router.beforeEach((to, from, next) => {
  // 有token的情况下去登陆页引导到首页 在用户登录的vue中设置了 this.$router.back()就不需要设置以下的代码
  // 以下代码有缺陷 当登陆以后不会反回上一级 而是直接回退到首页
  // if (to.push === '/login' && store.state.user.token) {
  //   next('/')
  // }
  // 如果是需要授权的页面
  if (AuthUrls.includes(to.path)) {
    // 进行验证身份
    if (store.state.user.token) {
      next()
    } else {
      // 拦截到登录
      next({
        path: '/login',
        // 从哪里来去哪里去
        query: {
          a: 1,
          b: 2,
          backto: to.fullPath// 就是要去访问地址
          // backto: to.path
        }
      })
    }
  } else {
    next()
  }
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
